package com.myjar.excel.v2;


import com.myjar.excel.serializer.ObjectSerializer;

import java.util.Collection;


public class POiContext<T> implements _Context<T> {

    private _Sheet sheet;
    private int readRow, readCell;
    private Logger<T> logger;

    // 写
    public POiContext(_Workbook workbook, String name) {
        sheet = workbook.createSheet(name);
        logger = new ReadLogger<>(workbook);
    }

    // 读
    public POiContext(_Workbook workbook, int index) throws ExcelException {
        sheet = workbook.getSheet(index);
        if (sheet == null) {
            throw new ExcelException("找不到对应index的sheet");
        }
        logger = new ReadLogger<>(workbook);
    }

    // 读
    public POiContext(_Workbook workbook) throws ExcelException {
        int index = workbook.sheetSize() - 1;
        if (index < 0)
            throw new ExcelException("空excel");
        sheet = workbook.getSheet(index);
        logger = new ReadLogger<>(workbook);
    }

    @Override
    public <K> void setVal(K t,ObjectSerializer<K> objectSerializer) throws Exception {
        _Cell cell1 = getCell(readRow, readCell);
        cell1.setVal(t, objectSerializer);
    }

    @Override
    public <K> K getVal(ObjectSerializer<K> objectSerializer) throws Exception {
        _Cell cell1 = getCell(readRow, readCell);
        return cell1.getVal(objectSerializer);
    }

    @Override
    public int rowIndex() {
        return readRow;
    }

    @Override
    public int cellIndex() {
        return readCell;
    }

    @Override
    public int cellSize() {
        _Row row = sheet.getRow(readCell);
        return row == null ? 0 : row.cellSize();
    }

    @Override
    public int rowSize() {
        return sheet.rowSize();
    }

    @Override
    public boolean hasMoreCell() {
        return cellSize() > readCell;
    }

    @Override
    public boolean hasMoreRow() {
        return rowSize() > readRow;
    }

    @Override
    public void toNextLineBegin() {
        readRow++;
        readCell = 0;
    }

    @Override
    public void toNextCell() {
        readCell++;
    }

    @Override
    public void move(int row, int cell) {
        readCell = cell;
        readRow = row;
    }


    @Override
    public void log(Throwable throwable) {
        logger.log(throwable, readRow, readCell);
    }

    @Override
    public void add(T t) {
        logger.push(t);
    }

    @Override
    public Collection<T> suc() {
        return logger.poll();
    }

    @Override
    public Logger<T> getLogger() {
        return logger;
    }


    private _Cell getCell(int row, int cell) {
        _Row row1 = this.sheet.getRow(row);
        row1 = row1.isNull() ?
                this.sheet.createRow(row) :
                row1;

        _Cell cell1 = row1.getCell(cell);
        cell1 = cell1.isNull()?
                row1.createCell(cell) :
                cell1;
        return cell1;
    }


}
